{% extends 'admin_panel/base.html' %}

{% block title %}编辑旅行记录 - 旅行记录管理系统{% endblock %}
{% block page_title %}编辑旅行记录{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">编辑旅行记录</h5>
            </div>
            <div class="card-body">
                <form method="post">
                    {% csrf_token %}
                    
                    {% if form.errors %}
                    <div class="alert alert-danger">
                        <strong>请修正以下错误：</strong>
                        <ul>
                            {% for field, errors in form.errors.items %}
                                {% for error in errors %}
                                    <li>{{ error }}</li>
                                {% endfor %}
                            {% endfor %}
                        </ul>
                    </div>
                    {% endif %}

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.title.id_for_label }}" class="form-label">标题 *</label>
                            <input type="text" class="form-control" id="{{ form.title.id_for_label }}" 
                                   name="{{ form.title.name }}" value="{{ form.title.value|default:'' }}" required>
                            <div class="form-text">旅行记录的标题</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.location.id_for_label }}" class="form-label">位置</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="{{ form.location.id_for_label }}" 
                                       name="{{ form.location.name }}" value="{{ form.location.value|default:'' }}">
                                <button type="button" class="btn btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#mapModal">
                                    <i class="bi bi-geo-alt"></i> 选择位置
                                </button>
                            </div>
                            <div class="form-text">旅行地点名称</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.latitude.id_for_label }}" class="form-label">纬度</label>
                            <input type="number" step="any" class="form-control" id="{{ form.latitude.id_for_label }}" 
                                   name="{{ form.latitude.name }}" value="{{ form.latitude.value|default:'' }}">
                            <div class="form-text">地理坐标纬度</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.longitude.id_for_label }}" class="form-label">经度</label>
                            <input type="number" step="any" class="form-control" id="{{ form.longitude.id_for_label }}" 
                                   name="{{ form.longitude.name }}" value="{{ form.longitude.value|default:'' }}">
                            <div class="form-text">地理坐标经度</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.start_date.id_for_label }}" class="form-label">开始日期 *</label>
                            <input type="date" class="form-control" id="{{ form.start_date.id_for_label }}" 
                                   name="{{ form.start_date.name }}" value="{{ form.start_date.value|date:'Y-m-d' }}" required>
                            <div class="form-text">旅行开始日期</div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label for="{{ form.end_date.id_for_label }}" class="form-label">结束日期</label>
                            <input type="date" class="form-control" id="{{ form.end_date.id_for_label }}" 
                                   name="{{ form.end_date.name }}" value="{{ form.end_date.value|date:'Y-m-d' }}">
                            <div class="form-text">旅行结束日期（可选）</div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="{{ form.description.id_for_label }}" class="form-label">描述</label>
                        <textarea class="form-control" id="{{ form.description.id_for_label }}" 
                                  name="{{ form.description.name }}" rows="5">{{ form.description.value|default:'' }}</textarea>
                        <div class="form-text">旅行的详细描述</div>
                    </div>

                    <!-- 图片管理区域 -->
                    <div class="mb-4">
                        <label class="form-label">图片管理</label>
                        <div class="card">
                            <div class="card-body">
                                <!-- 现有图片 -->
                                {% if object.images %}
                                <div class="mb-3">
                                    <h6 class="text-muted mb-2">现有图片</h6>
                                    <div id="existing_images" class="d-flex flex-wrap gap-2 mb-3">
                                        {% for image_url in object.images %}
                                        <div class="image-preview-item existing-image position-relative" data-url="{{ image_url }}">
                                            <img src="{{ image_url }}" alt="现有图片">
                                            {% if object.main_image_index == forloop.counter0 %}
                                            <div class="position-absolute top-0 start-0 m-1">
                                                <span class="badge bg-primary">
                                                    <i class="bi bi-star-fill me-1"></i>主图
                                                </span>
                                            </div>
                                            {% endif %}
                                            <button type="button" class="btn btn-danger btn-sm remove-existing-image" style="position: absolute; top: 5px; right: 5px; width: 24px; height: 24px; padding: 0; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                                                <i class="bi bi-x" style="font-size: 14px; line-height: 1;"></i>
                                            </button>
                                        </div>
                                        {% endfor %}
                                    </div>
                                    <input type="hidden" id="retained_images" name="retained_images" value="{{ object.images|join:',' }}">
                                    <input type="hidden" id="deleted_images" name="deleted_images" value="">
                                </div>
                                {% endif %}
                                
                                <!-- 新增图片 -->
                                <div>
                                    <h6 class="text-muted mb-2">新增图片</h6>
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <span class="text-muted">
                                            已选择 <span id="file_count">0</span> / <span id="max_files">50</span> 张图片
                                            (<span id="remaining_files">50</span> 张剩余)
                                        </span>
                                        <label for="image_upload" class="btn btn-primary btn-sm mb-0">
                                            <i class="bi bi-plus me-1"></i>选择图片
                                        </label>
                                        <input type="file" id="image_upload" accept="image/*" multiple 
                                               style="display: none;">
                                    </div>
                                    
                                    <div id="image_preview" class="d-flex flex-wrap gap-2"></div>
                                    
                                    <small class="text-muted">
                                        支持 JPG, PNG, GIF 格式，每张图片最大 5MB，最多 50 张
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 主图选择区域 -->
                    <div class="mb-3">
                        <label class="form-label">选择主图</label>
                        <div class="card">
                            <div class="card-body">
                                <div class="alert alert-info mb-3">
                                    <small>主图将作为旅行记录的封面图片显示</small>
                                </div>
                                <div id="main_image_selector" class="d-flex flex-wrap gap-2 mb-3">
                                    {% for image_url in object.images %}
                                    <div class="main-image-option {% if forloop.counter0 == object.main_image_index %}selected{% endif %}" 
                                         data-index="{{ forloop.counter0 }}">
                                        <img src="{{ image_url }}" alt="主图选项">
                                        {% if forloop.counter0 == object.main_image_index %}
                                        <div class="selected-badge">✓</div>
                                        {% endif %}
                                    </div>
                                    {% endfor %}
                                </div>
                                <input type="hidden" id="main_image_index" name="main_image_index" 
                                       value="{{ object.main_image_index|default:'' }}">
                                <small class="text-muted">点击图片设为封面主图</small>
                            </div>
                        </div>
                    </div>

                    <div class="d-flex justify-content-between">
                        <a href="{% url 'admin_panel:admin_travel_detail' object.pk %}" class="btn btn-secondary">
                            <i class="bi bi-arrow-left me-2"></i>取消
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle me-2"></i>保存更改
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
{% include 'admin_panel/map_selector.html' %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 日期验证：结束日期不能早于开始日期
    const startDateInput = document.getElementById('{{ form.start_date.id_for_label }}');
    const endDateInput = document.getElementById('{{ form.end_date.id_for_label }}');
    
    function validateDates() {
        if (startDateInput.value && endDateInput.value) {
            const startDate = new Date(startDateInput.value);
            const endDate = new Date(endDateInput.value);
            
            if (endDate < startDate) {
                endDateInput.setCustomValidity('结束日期不能早于开始日期');
            } else {
                endDateInput.setCustomValidity('');
            }
        }
    }
    
    startDateInput.addEventListener('change', validateDates);
    endDateInput.addEventListener('change', validateDates);

    // 图片管理功能
    const imageUpload = document.getElementById('image_upload');
    const imagePreview = document.getElementById('image_preview');
    const selectedFiles = [];
    const maxFiles = 50;
    const retainedImagesInput = document.getElementById('retained_images');
    const deletedImagesInput = document.getElementById('deleted_images');
    let retainedImages = retainedImagesInput ? retainedImagesInput.value.split(',') : [];
    let deletedImages = [];

    // 现有图片删除处理
    document.querySelectorAll('.remove-existing-image').forEach(button => {
        button.addEventListener('click', function() {
            const imageItem = this.closest('.existing-image');
            const imageUrl = imageItem.dataset.url;
            
            // 添加到删除列表
            if (!deletedImages.includes(imageUrl)) {
                deletedImages.push(imageUrl);
            }
            
            // 从保留列表中移除
            retainedImages = retainedImages.filter(url => url !== imageUrl);
            
            // 隐藏图片项
            imageItem.style.display = 'none';
            
            // 更新隐藏字段
            updateHiddenFields();
        });
    });

    // 更新隐藏字段
    function updateHiddenFields() {
        if (retainedImagesInput) {
            retainedImagesInput.value = retainedImages.join(',');
        }
        if (deletedImagesInput) {
            deletedImagesInput.value = deletedImages.join(',');
        }
    }

    if (imageUpload && imagePreview) {
        // 文件选择处理
        imageUpload.addEventListener('change', function(e) {
            const files = e.target.files;
            if (!files.length) return;

            // 检查文件数量限制
            const totalFiles = selectedFiles.length + files.length;
            const currentTotal = retainedImages.length + selectedFiles.length;
            
            if (currentTotal + files.length > maxFiles) {
                alert(`最多只能上传 ${maxFiles} 张图片`);
                this.value = '';
                return;
            }

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    alert('请选择图片文件');
                    continue;
                }

                // 验证文件大小（最大5MB）
                if (file.size > 5 * 1024 * 1024) {
                    alert('图片大小不能超过5MB');
                    continue;
                }

                selectedFiles.push(file);
                createImagePreview(file, selectedFiles.length - 1);
            }

            this.value = '';
            updateFileInputState();
        });

        // 创建图片预览
        function createImagePreview(file, index) {
            const previewUrl = URL.createObjectURL(file);
            
            const previewItem = document.createElement('div');
            previewItem.className = 'image-preview-item';
            previewItem.innerHTML = `
                <img src="${previewUrl}" alt="预览图片">
                <button type="button" class="btn btn-danger btn-sm remove-image" data-index="${index}">
                    <i class="bi bi-x"></i>
                </button>
            `;
            
            imagePreview.appendChild(previewItem);

            // 添加删除事件
            previewItem.querySelector('.remove-image').addEventListener('click', function() {
                const index = parseInt(this.dataset.index);
                removeImage(index);
            });
        }

        // 删除图片
        function removeImage(index) {
            // 释放对象URL
            const img = imagePreview.children[index].querySelector('img');
            URL.revokeObjectURL(img.src);
            
            // 从数组中移除
            selectedFiles.splice(index, 1);
            
            // 重新渲染预览
            refreshImagePreviews();
            updateFileInputState();
        }

        // 刷新所有预览
        function refreshImagePreviews() {
            imagePreview.innerHTML = '';
            selectedFiles.forEach((file, index) => {
                createImagePreview(file, index);
            });
        }

        // 更新文件输入状态
        function updateFileInputState() {
            const currentTotal = retainedImages.length + selectedFiles.length;
            const remaining = maxFiles - currentTotal;
            
            document.getElementById('file_count').textContent = selectedFiles.length;
            document.getElementById('max_files').textContent = maxFiles;
            document.getElementById('remaining_files').textContent = remaining;
            
            if (remaining === 0) {
                imageUpload.disabled = true;
                imageUpload.setAttribute('title', '已达到最大上传数量');
            } else {
                imageUpload.disabled = false;
                imageUpload.removeAttribute('title');
            }
        }

        // 表单提交处理
        const form = document.querySelector('form');
        form.addEventListener('submit', function(e) {
            // 创建FormData对象
            const formData = new FormData(this);
            
            // 添加所有图片文件
            selectedFiles.forEach((file, index) => {
                formData.append('new_images', file);
            });

            // 使用fetch提交表单
            e.preventDefault();
            
            const submitBtn = this.querySelector('button[type="submit"]');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-arrow-repeat spinner"></i> 保存中...';

            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                }
            })
            .then(response => {
                if (response.redirected) {
                    window.location.href = response.url;
                } else if (response.ok) {
                    // 检查是否是JSON响应
                    const contentType = response.headers.get('content-type');
                    if (contentType && contentType.includes('application/json')) {
                        return response.json();
                    } else {
                        // 如果不是JSON，直接重定向
                        window.location.href = '{% url "admin_panel:admin_travel_list" %}';
                        return null;
                    }
                } else {
                    throw new Error('提交失败');
                }
            })
            .then(data => {
                if (data && data.success) {
                    window.location.href = data.redirect_url;
                } else if (!data) {
                    // 已经重定向，不需要处理
                } else {
                    throw new Error(data.error || '提交失败');
                }
            })
            .catch(error => {
                alert('保存失败: ' + error.message);
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="bi bi-check-circle me-2"></i>保存更改';
            });
        });

        // 初始化文件输入状态
        updateFileInputState();

        // 主图选择功能
        setupMainImageSelector();
    }

    // 主图选择功能
    function setupMainImageSelector() {
        const selector = document.getElementById('main_image_selector');
        const hiddenInput = document.getElementById('main_image_index');
        
        if (!selector || !hiddenInput) return;
        
        // 点击选择主图
        selector.addEventListener('click', function(e) {
            const option = e.target.closest('.main-image-option');
            if (!option) return;
            
            const index = option.dataset.index;
            
            // 移除之前的选择
            selector.querySelectorAll('.main-image-option').forEach(opt => {
                opt.classList.remove('selected');
                opt.querySelector('.selected-badge')?.remove();
            });
            
            // 设置新的选择
            option.classList.add('selected');
            const badge = document.createElement('div');
            badge.className = 'selected-badge';
            badge.innerHTML = '✓';
            option.appendChild(badge);
            
            // 更新隐藏字段
            hiddenInput.value = index;
        });
    }

    // 在图片预览更新时刷新主图选择器
    function refreshMainImageSelector() {
        const selector = document.getElementById('main_image_selector');
        const hiddenInput = document.getElementById('main_image_index');
        if (!selector || !hiddenInput) return;
        
        // 获取所有图片URL（现有图片 + 新上传预览）
        const allImages = [];
        
        // 添加现有图片（保留的图片）
        if (retainedImages && retainedImages.length > 0) {
            allImages.push(...retainedImages);
        }
        
        // 重新渲染选择器
        selector.innerHTML = '';
        if (allImages.length === 0) {
            selector.innerHTML = '<div class="text-muted">请先上传图片</div>';
            return;
        }
        
        allImages.forEach((imgUrl, index) => {
            const isSelected = index === parseInt(hiddenInput.value);
            const option = document.createElement('div');
            option.className = `main-image-option ${isSelected ? 'selected' : ''}`;
            option.dataset.index = index;
            option.innerHTML = `
                <img src="${imgUrl}" alt="主图选项">
                ${isSelected ? '<div class="selected-badge">✓</div>' : ''}
            `;
            selector.appendChild(option);
        });

        // 重新绑定点击事件
        setupMainImageSelector();
    }

    // 重写图片预览相关函数以包含主图选择器刷新
    const originalCreateImagePreview = createImagePreview;
    const originalRemoveImage = removeImage;
    const originalRefreshImagePreviews = refreshImagePreviews;

    createImagePreview = function(file, index) {
        originalCreateImagePreview(file, index);
        refreshMainImageSelector();
    };

    removeImage = function(index) {
        originalRemoveImage(index);
        refreshMainImageSelector();
    };

    refreshImagePreviews = function() {
        originalRefreshImagePreviews();
        refreshMainImageSelector();
    };

    // 监听现有图片删除事件，刷新主图选择器
    document.querySelectorAll('.remove-existing-image').forEach(button => {
        const originalClick = button.onclick;
        button.onclick = function() {
            if (originalClick) originalClick.call(this);
            setTimeout(refreshMainImageSelector, 100);
        };
    });
});
</script>
{% endblock %}
